package me.shurufa.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.shurufa.R;
import me.shurufa.model.Book;
import me.shurufa.model.BookInfoResponse;
import me.shurufa.model.Catalog;
import me.shurufa.model.CatalogArrayListResponse;
import me.shurufa.model.CatalogResponse;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.NetworkConstants;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.popupwindow.WheelPopWindow;

/**
 * 如果是新建书摘 从添加书摘本AddDigestActivity跳转过来
 * 如果是添加书摘 是从BitmapTransformActivity或BitmapNoTransformActivity跳转的
 * 通过bid获取目录 如果目录为空则手动添加目录 添加目录成功后跳转至AddDigestCompleteActivity
 *
 * @FileName: me.shurufa.activities.AddDigestMenuActivity.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-02-16 18:13
 */
public class AddDigestMenuActivity extends BaseActivity implements WheelPopWindow.OnCompleteClickListener, View.OnClickListener {

    @Bind(R.id.txt_book_name)
    TextView txtBookName;
    @Bind(R.id.book_name_edit)
    TextView bookNameEdit;
    @Bind(R.id.txt_author_name)
    TextView txtAuthorName;
    @Bind(R.id.author_name_edit)
    TextView authorNameEdit;
    @Bind(R.id.txt_publisher_name)
    TextView txtPublisherName;
    @Bind(R.id.publisher_name_edit)
    TextView publisherNameEdit;
    @Bind(R.id.txt_part)
    TextView txtPart;
    @Bind(R.id.part_name)
    TextView partName;
    @Bind(R.id.popup_arrow)
    ImageView popupArrow;
    @Bind(R.id.part_layout)
    RelativeLayout partLayout;
    @Bind(R.id.edit_part)
    EditText editPart;
    @Bind(R.id.menu_name)
    EditText menuName;
    @Bind(R.id.write_part_layout)
    RelativeLayout writePartLayout;
    @Bind(R.id.txt_page_name)
    TextView txtPageName;
    @Bind(R.id.page_number_edit)
    EditText pageNumberEdit;
    @Bind(R.id.layout_input_layout)
    LinearLayout layoutInputLayout;
    @Bind(R.id.complete_layout)
    RelativeLayout completeLayout;
    private Book mBook;//从Intent获取的书本

    private long mMenuId;
    private boolean hasMenu;
    WheelPopWindow popWindow;
    private Catalog currentCatalog;

    private String mNote;//笔记
    private String mContent;//书摘内容
    private boolean isSend;//发布状态 publish or save
    private String pageNumber;

    private InputMethodManager imm;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_add_digest_menu;
        super.onCreate(savedInstanceState);

//       getIntent获取图书及其他信息
        String strBook = getIntent().getStringExtra(Constants.ARG_BOOK);
        if (!TextUtils.isEmpty(strBook))
            mBook = new Gson().fromJson(strBook, Book.class);
        initData();
        initUI();
    }

    private void initUI() {
        imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        titleTextView.setText(getString(R.string.make_digest));
        SpannableString inputSpannable = new SpannableString(getString(R.string.input));
        inputSpannable.setSpan(new ForegroundColorSpan(Color.parseColor("#d70c17")),
                0, inputSpannable.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        menuName.setHint(TextUtils.concat(getString(R.string.not_find_part),inputSpannable));
        popupArrow.setOnClickListener(this);
        SpannableString span = new SpannableString(getString(R.string.select_write));
        span.setSpan(new RelativeSizeSpan(0.7f),0,span.length(),Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        txtPageName.setText(TextUtils.concat(getString(R.string.page_number),span));
        completeLayout.setOnClickListener(this);
    }

    private void initData() {

        mContent = getIntent().getStringExtra(Constants.ARG_DIGEST_CONTENT);
        mNote = getIntent().getStringExtra(Constants.ARG_DIGEST_NOTE);
        isSend = getIntent().getBooleanExtra(Constants.ARG_DIGEST_STATE,true);

        if (mBook != null) {
            searchMenuByBookId(mBook.book_id);
            new RequestServerTask<BookInfoResponse>(BookInfoResponse.class) {

                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<>();
                    params.put("bookId", mBook.book_id);
                    return HttpUtil.post(NetworkConstants.GET_BOOK_INFO, params);
                }

                @Override
                protected void onSuccess(BookInfoResponse result) {

                    if (!TextUtils.isEmpty(result.data.author))
                        authorNameEdit.setText(result.data.author);
                    if (!TextUtils.isEmpty(result.data.title))
                        bookNameEdit.setText(result.data.title);
                    if (!TextUtils.isEmpty(result.data.publisher))
                        publisherNameEdit.setText(result.data.publisher);
                }
            }.start();
        }
    }

    /**
     * 通过Id搜索目录
     * 需要注意 如果有mBook对象 直接通过mBook.bid获取目录 mBook对象是从书架页面点击获取的
     * 如果没有mBook对象 在搜索成功后点击item 搜索的为external_book_id;
     *
     * @param bookId
     */
    private void searchMenuByBookId(final long bookId) {
        hasMenu = false;
        mMenuId = 0L;
        popWindow = null;
        new RequestServerTask<CatalogArrayListResponse>(CatalogArrayListResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("bookId", bookId);
                return HttpUtil.post(NetworkConstants.GET_BOOK_MENU, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }


            @Override
            protected void onSuccess(CatalogArrayListResponse result) {
                currentCatalog = null;
                //没有获取到目录
                if (result.data == null || result.data.size() == 0) {
                    writePartLayout.setVisibility(View.VISIBLE);
                    partLayout.setVisibility(View.GONE);
                    hasMenu = false;
                } else {
                    hasMenu = true;
                    writePartLayout.setVisibility(View.GONE);
                    partLayout.setVisibility(View.VISIBLE);
                    popWindow = new WheelPopWindow(AddDigestMenuActivity.this, result.data);
                    popWindow.setOnCompleteClickListener(AddDigestMenuActivity.this);
                }
            }
        }.start();
    }

    /**
     * popWindow 点击完成按钮事件
     */
    @Override
    public void onCompleteClicked() {
        if (popWindow != null) {
            currentCatalog = popWindow.getCurrentData();
            partName.setText(currentCatalog.title);
            mMenuId = currentCatalog.id;
            popWindow.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.popup_arrow:
                imm.hideSoftInputFromWindow(v.getWindowToken(),0);
                if (popWindow != null) {
                    popWindow.init();
                    popWindow.showPickerWindow(v, 100);
                }
                break;
            case R.id.complete_layout:
                if (checkCommitInfo()){
                    commitDigestInfoCheckHasMenu();
                }
                break;
        }
    }

    //判断有没有目录 如果没有目录先添加目录
    private void commitDigestInfoCheckHasMenu() {
        if (!hasMenu){
            new RequestServerTask<CatalogResponse>(CatalogResponse.class,this,getString(R.string.commit_pls_wait)){

                @Override
                protected String requestServer() {
                    Map<String,Object> params = new HashMap<String, Object>();
                    params.put("token", Global.currentUser.token);
                    params.put("bookId",mBook.book_id);
                    params.put("title",menuName.getText().toString().trim());
                    params.put("menuOrder", editPart.getText().toString().trim());
                    return HttpUtil.post(NetworkConstants.ADD_MENU,params);
                }

                @Override
                protected void onSuccess(CatalogResponse result) {
                    // setMenuId = result.menuId
                    mMenuId = result.data.id;
                    commitDigest();
                }
            }.start();
        }else {
            commitDigest();
        }
    }

    private void commitDigest() {
        new RequestServerTask<BaseResponse>(BaseResponse.class,this,getString(R.string.commit_pls_wait)){

            @Override
            protected String requestServer() {
                Map<String,Object> params = new HashMap<String, Object>();
                params.put("bookId",mBook.book_id);
                params.put("token",Global.currentUser.token);
                params.put("menuId",mMenuId);
                if (!TextUtils.isEmpty(pageNumberEdit.getText().toString().trim())) {
                    params.put("pageNumber", pageNumber);//TODO 添加后不显示
                    LogUtils.kLog().e("pageNumber:"+pageNumber);
                }
                params.put("content",mContent);
                params.put("publishState",isSend?"publish":"save");
                if (!TextUtils.isEmpty(mNote))
                    params.put("note",mNote);
                return HttpUtil.post(NetworkConstants.ADD_DIGEST,params);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                Intent intent = new Intent(AddDigestMenuActivity.this,AddDigestCompleteActivity.class);
                intent.putExtra(Constants.ARG_BOOK_TITLE,bookNameEdit.getText().toString());
                startActivity(intent);
            }
        }.start();
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction().equals(Constants.ACTION_ADD_DIGEST_COMPLETE))
            finish();
    }

    private boolean checkCommitInfo() {

        if (TextUtils.isEmpty(mContent)){
            Utils.showToast(R.string.digest_content_not_be_empty);
            return false;
        }

        if (hasMenu&&mMenuId==0L){
            Utils.showToast(R.string.menu_info_is_empty);
            return false;
        }
        if (!hasMenu&&TextUtils.isEmpty(editPart.getText().toString().trim())
                &&TextUtils.isEmpty(menuName.getText().toString().trim())) {
            Utils.showToast(R.string.part_and_menu_is_empty);
            return false;
        }
        return true;
    }
}
